import 'dart:async';

import 'package:sqflite_common_ffi/sqflite_ffi.dart';

import '../../chat/MessageModel.dart';
import 'DBManager.dart';

class MessageDao{
  static late Database db;

  MessageDao._();

  static final MessageDao _instance = MessageDao._();

  static MessageDao get instance {
    return _instance;
  }

  Future init() async {
    db = await DBManager.getInstance().getDatabase;
  }

  ///插入数据
  static Future<int> insert(MessageModel bean) async{
    return await db.insert(DBManager.messageTable, bean.toJson());
  }

  ///修改数据
  // Future<int> update() async{
  //   Database db = await database;
  //   await db.update(table, values)
  // }

  ///删除数据
  static Future<int> delete(String id) async{
    Database db = await DBManager.getInstance().getDatabase;
    return await db.delete(DBManager.messageTable,where:'${DBManager.id} = ?',whereArgs:[id]);
  }

  ///删除全部数据
  static  Future<int> deleteAll() async{
    Database db = await DBManager.getInstance().getDatabase;
    return await db.delete(DBManager.messageTable,where:'${DBManager.id} != ?',whereArgs:[0]);
  }

  ///查询数据
  static Future<List<MessageModel>> query(int id) async {
    Database db = await DBManager.getInstance().getDatabase;
    var result = await db.query(DBManager.messageTable, where: '${DBManager.id} = ?', whereArgs: [id]);
    if (result.isNotEmpty) {
      return result.map((e) => MessageModel.fromJson(e)).toList();
    } else {
      return [];
    }
  }

  ///根据id查询判断是否存在
  static Future<bool> isExist(int id) async {
    Database db = await DBManager.getInstance().getDatabase;
    var result = await db.query(DBManager.messageTable, where: '${DBManager.id} = ?', whereArgs: [id]);
    if (result.isNotEmpty) {
      return true;
    } else {
      return false;
    }
  }

  ///查询所有数据
  static  Future<List<MessageModel>> queryAll() async {
    Database db = await DBManager.getInstance().getDatabase;
    var result = await db.query(DBManager.messageTable);
    if (result.isNotEmpty) {
      return result.map((e) => MessageModel.fromJson(e)).toList();
    } else {
      return [];
    }
  }
}
